<?php

namespace app\home\controller;

use app\common\controller\Home;

class Subject extends Home
{
    public $NoLogin = ['index', 'info', 'likes', 'play'];

    public function __construct()
    {
        parent::__construct();

        $this->SubjectModel = model('Subject.Subject');
        $this->TeacherModel = model('Teacher.Teacher');
        $this->CategoryModel = model('Subject.Category');
        $this->ChapterModel = model('Subject.Chapter');
        $this->CommentModel = model('Subject.Comment');
        $this->OrderModel = model('Subject.Order');
        $this->ReceiveModel = model('Coupon.Receive');
        $this->RecordModel = model('Business.Record');
        $this->BusinessModel = model('Business.Business');
        $this->CommissionModel = model('Business.Commission');
    }

    //课程搜索
    public function index()
    {
        if($this->request->isAjax())
        {
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');
            $keywords = $this->request->param('keywords', '', 'trim');

            //偏移量
            $start = ($page-1)*$limit;

            $where = [];

            if(!empty($keywords))
            {
                $where['title'] = ['LIKE', "%$keywords%"];
            }

            //查询数据总条数
            $count = $this->SubjectModel->where($where)->count();

            //查询数据
            $list = $this->SubjectModel
                    ->with(['category', 'teacher'])
                    ->where($where)
                    ->limit($start, $limit)
                    ->select();

            $data = [
                'count' => $count,
                'list' => $list
            ];

            if($list)
            {
                //成功返回
                $this->success('返回列表', null, $data);
                exit;
            }else
            {
                //失败返回
                $this->error('暂无数据', null, $data);
                exit;
            }
        }

        return $this->view->fetch();
    }

    //课程详情页面
    public function info()
    {
        $subid = $this->request->param('subid', 0, 'trim');

        //判断课程信息是否存在
        $subject = $this->SubjectModel->with(['category'])->find($subid);

        if(!$subject)
        {
            $this->error('课程不存在');
            exit;
        }

        //给点赞状态设置一个属性嵌入到课程资料中
        $subject['likes_active'] = false;

        //获取登录信息
        $login = $this->IsLogin(false);

        //判断是否已购买课程
        $buy = false;

        if($login)
        {
            $likes = isset($subject['likes']) ? trim($subject['likes']) : '';
            $likes = explode(',', $likes);

            //增加一个自定义属性
            $subject['likes_active'] = in_array($login['id'], $likes) ? true : false;

            //查询当前用户是否有购买过
            $where = ['subid' => $subid, 'busid' => $login['id']];
            $check = $this->OrderModel->where($where)->find();
            $buy = $check ? true : false;
        }

        //查询章节
        $chapter = $this->ChapterModel->where(['subid' => $subid])->select();

        //老师信息
        $teacherid = isset($subject['teacherid']) ? trim($subject['teacherid']) : 0;
        $teacher = $this->TeacherModel->find($teacherid);

        if($this->request->isAjax())
        {
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');
            $keywords = $this->request->param('keywords', '', 'trim');

            //偏移量
            $start = ($page-1)*$limit;

            $where = ['subid' => $subid];

            if(!empty($keywords))
            {
                $where['content'] = ['LIKE', "%$keywords%"];
            }

            //查询数据总条数
            $count = $this->CommentModel->where($where)->count();

            //查询数据
            $list = $this->CommentModel
                ->with(['business'])
                ->where($where)
                ->order('id desc')
                ->limit($start, $limit)
                ->select();

            $data = [
                'count' => $count,
                'list' => $list
            ];

            if($list)
            {
                //成功返回
                $this->success('返回列表', null, $data);
                exit;
            }else
            {
                //失败返回
                $this->error('暂无数据', null, $data);
                exit;
            }
        }

        // var_dump($subject->toArray());
        // exit;

        //赋值
        $this->assign([
            'subject' => $subject,
            'chapter' => $chapter,
            'teacher' => $teacher,
            'buy' => $buy,
        ]);
        
        return $this->view->fetch();
    }

    //课程点赞
    public function likes()
    {
        if($this->request->isAjax())
        {
            $subid = $this->request->param('subid', 0, 'trim');

            $subject = $this->SubjectModel->find($subid);

            if(!$subject)
            {
                $this->error('课程不存在');
                exit;
            }

            //判断是否有登录
            $login = $this->IsLogin(false);

            if(!$login)
            {
                $this->error('请先登录');
                exit;
            }

            // 9,11,12,13,14,17,15,10,22 => 用户id
            $likes = isset($subject['likes']) ? trim($subject['likes']) : '';

            // [9,11,12,13,14,17,15,10,22]
            $likes = explode(',', $likes);
            $action = $msg = '';
            
            //如果用户ID在数组中就说明点过赞,不在就说明没有点赞
            // var_dump(in_array($login['id'], $likes));
            // exit;
            
            // [9,11,12,13,14,17,15,10,22]
            if(in_array($login['id'], $likes))
            {
                //已经点过赞，现在要取消点赞
                $key = array_search($login['id'], $likes);

                //删除数组元素
                unset($likes[$key]);

                //取消动作
                $action = 'cancel';
                $msg = '取消点赞';
            }else
            {
                //他没有点过赞，现在要点赞
                $likes[] = $login['id'];// [9,11,12,13,14,17,15,10,22]
                
                $action = 'active';
                $msg = '点赞';
            }


            $likes = array_filter($likes);
            $likes = array_unique($likes);

            $data = [
                'id' => $subid,
                'likes' => implode(',', $likes)// 9,11,12,13,14,17,15,10,22
            ];

            //更新语句
            $result = $this->SubjectModel->isUpdate(true)->save($data);

            if($result === FALSE)
            {
                $this->error("{$msg}失败");
                exit;
            }else
            {
                $this->success("{$msg}成功", null, ['action' => $action]);
                exit;
            }
        }
    }

    //课程购买
    public function confirm()
    {
        $subid = $this->request->param('subid', 0, 'trim');

        //查询一下课程是否存在
        $subject = $this->SubjectModel->with(['category', 'teacher'])->find($subid);

        if(!$subject)
        {
            $this->error('课程不存在');
            exit;
        }

        //查询当前这个人领取过的优惠券
        $where = [
            'busid' => $this->view->AutoLogin['id'],
            'receive.status' => '1'
        ];

        $coupon = $this->ReceiveModel->with(['coupon'])->where($where)->select();

        if($this->request->isPost())
        {
            $couid = $this->request->param('coupon', 0, 'trim');
            $pay = $this->request->param('pay', 'money', 'trim');
            $total = isset($subject['price']) ? trim($subject['price']) : 0;

            // subject_order 用户订单表
            // business_record 用户消费记录
            // business 用户表
            // coupon_receive 优惠券领取记录表

            $this->OrderModel->startTrans();
            $this->RecordModel->startTrans();
            $this->BusinessModel->startTrans();
            $this->ReceiveModel->startTrans();
            $this->CommissionModel->startTrans();


            //查询是否有选择优惠券
            $where = ['receive.id' => $couid, 'receive.status' => '1'];
            $coupon = $this->ReceiveModel->with(['coupon'])->where($where)->find();

            if($coupon)
            {
                //获取到折扣率
                $rate = isset($coupon['coupon']['rate']) ? trim($coupon['coupon']['rate']) : 1;
                
                //两个高精度数字相乘
                $total = bcmul($total, $rate);
            }

            //插入订单表
            $OrderData = [
                'subid' => $subid,
                'busid' => $this->view->AutoLogin['id'],
                'pay' => $pay,
                'total' => $total,
                'code' => build_code("ST"),
            ];


            //插入到订单表
            $OrderStatus = $this->OrderModel->validate('common/Subject/Order')->save($OrderData);

            if($OrderStatus === FALSE)
            {
                $this->error($this->OrderModel->getError());
                exit;
            }

            //消费记录
            $title = $subject['title'];
            $content = "购买了【{$title}】,花费了￥ $total 元";
            $RecordData = [
                'total' => "-$total",
                'content' => $content,
                'busid' => $this->view->AutoLogin['id']
            ];

            $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);

            if($RecordStatus === FALSE)
            {
                $this->OrderModel->rollback();
                $this->error($this->RecordModel->rollback());
                exit;
            }

            //如果是余额支付就需要更新用户余额字段
            if($pay == "money")
            {
                //减去消费的金额 剩下的余额
                $money = bcsub($this->view->AutoLogin['money'], $total);

                $BusinessData = [
                    'id' => $this->view->AutoLogin['id'],
                    'money' => $money
                ];

                $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($BusinessData);

                if($BusinessStatus === FALSE)
                {
                    $this->RecordModel->rollback();
                    $this->OrderModel->rollback();
                    $this->error('个人余额更新失败');
                    exit;
                }
            }

            //如果有选择优惠券那么就要更新优惠券使用状态
            if($coupon)
            {
                $ReceiveData = [
                    'id' => $couid,
                    'status' => '0'
                ];

                $ReceiveStatus = $this->ReceiveModel->isUpdate(true)->save($ReceiveData);

                if($ReceiveStatus === FALSE)
                {
                    $this->BusinessModel->rollback();
                    $this->RecordModel->rollback();
                    $this->OrderModel->rollback();
                    $this->error('优惠券状态更新失败');
                    exit;
                }
            }

            //判断是否有推荐人可以得到佣金
            $parentid = $this->view->AutoLogin['parentid'] ? trim($this->view->AutoLogin['parentid']) : 0;
            $parent = $this->BusinessModel->find($parentid);
            if($parent)
            {
                //佣金比率
                $AmountRate = config('site.AmountRate');
                
                //消费金额*佣金比率 = 转给推荐人
                $amount = bcmul($total, $AmountRate);

                //插入佣金记录
                $CommissionData = [
                    'orderid' => $this->OrderModel->id, //获取插入最后一条的自增ID
                    'busid' => $this->view->AutoLogin['id'],
                    'parentid' => $parentid,
                    'type' => 'subject', //买课程的佣金
                    'stauts' => '0', //未提现
                    'amount' => $amount, //佣金
                ];

                $CommissionStatus = $this->CommissionModel->save($CommissionData);

                if($CommissionStatus === FALSE)
                {
                    $this->ReceiveModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->RecordModel->rollback();
                    $this->OrderModel->rollback();
                    $this->error('推荐信息存储失败');
                    exit;
                }
            }

            if($OrderStatus === FALSE || $RecordStatus === FALSE)
            {
                $this->CommissionModel->rollback();
                $this->ReceiveModel->rollback();
                $this->BusinessModel->rollback();
                $this->RecordModel->rollback();
                $this->OrderModel->rollback();
                $this->error('推荐信息存储失败');
                exit;
            }else
            {
                $this->OrderModel->commit();
                $this->RecordModel->commit();
                $this->BusinessModel->commit();
                $this->ReceiveModel->commit();
                $this->CommissionModel->commit();
                $this->success('购买课程成功', url('home/subject/info', ['subid' => $subid]));
                exit;
            }
        }
        
        $this->assign([
            'subject' => $subject,
            'coupon' => json_encode($coupon)
        ]);

        return $this->view->fetch();
    }

    //课程播放
    public function play()
    {
        if($this->request->isAjax())
        {
            $cid = $this->request->param('cid', 0, 'trim');

            //查询一下这个章节是否存在
            $chapter = $this->ChapterModel->find($cid);

            if(!$chapter)
            {
                $this->error('章节不存在');
                exit;
            }

            //判断是否有登录
            $login = $this->IsLogin(false);

            if(!$login)
            {
                $this->error('请先登录');
                exit;
            }

            //查找当前用户是否购买过订单
            $where = [
                'subid' => $chapter['subid'],
                'busid' => $login['id']
            ];

            $order = $this->OrderModel->where($where)->find();

            if(!$order)
            {
                $this->error('请先购买课程');
                exit;
            }

            $this->success('返回章节的信息', null, $chapter['url_text']);
            exit;
        }
    }


}
